package com.rabdsquirlz.wootoffreader;

import java.net.URL;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ViewFlipper;



public class WootOffReader extends Activity implements OnGestureListener
{
	ViewFlipper flip;
	private GestureDetector scanner;
	final String shirt = "http://www.shirt.woot.com/salerss.aspx";
	final String woot = "http://www.woot.com/salerss.aspx";
	final String wine = "http://www.wine.woot.com/salerss.aspx";
	final String kids = "http://www.kids.woot.com/salerss.aspx";
	final String sellout = "http://www.sellout.woot.com/salerss.aspx";
	
	private Handler handler = new Handler();
	public String buyUrl0, buyUrl1, buyUrl2, buyUrl3, buyUrl4, buyUrl;
	
	public static final int ABOUT_MENU = 0;
    public static final int HELP_MENU = 1;
    public static final int PREFERENCE_MENU = 2;
    public static final int EXIT_MENU = 3;
    public static final String PREFERENCES = "My Preferences"; 
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main2);
        
        flip = (ViewFlipper)findViewById(R.id.flip);
        
        scanner = new GestureDetector(this);   
        
        new Thread(new Runnable() {
            public void run() {
              Refresh(0);
            }
          }).start();
        
        new Thread(new Runnable() {
            public void run() {
              Refresh(1);
            }
          }).start();
        
        new Thread(new Runnable() {
            public void run() {
              Refresh(2);
            }
          }).start();
        
        new Thread(new Runnable() {
            public void run() {
              Refresh(3);
            }
          }).start();
        
        new Thread(new Runnable() {
            public void run() {
              Refresh(4);
            }
          }).start();

    }
    
    @Override
    public boolean onCreateOptionsMenu (Menu menu)
    {
    	menu.add(0, ABOUT_MENU, 1, "About").setIcon(R.drawable.about);
    	menu.add(0, PREFERENCE_MENU, 0, "Preferences").setIcon(R.drawable.preferences);
    	menu.add(0, EXIT_MENU, 2, "Exit").setIcon(R.drawable.quit);
    	return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
    	switch(item.getItemId())
    	{
    		case ABOUT_MENU:
    			show_about();
    			return true;
    		case PREFERENCE_MENU:
    			show_pref();
    			return true;
    		case EXIT_MENU:
    			quit();
    			return true;
    		default:
    			return false;
    	}
    }
    /*
    * shows the quit dialog box
    */
    private void quit()
    {
    	AlertDialog alert;
    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
    	builder.setMessage("Are you sure you want to exit?")
    		.setCancelable(false)
    		.setTitle("Exit")
    		.setPositiveButton("Yes", new DialogInterface.OnClickListener() 
    		{
    			public void onClick(DialogInterface dialog, int id) 
    			{
    				WootOffReader.this.finish();
    			}
    		})
    			.setNegativeButton("No", new DialogInterface.OnClickListener() {
    				public void onClick(DialogInterface dialog, int id) {
    					dialog.cancel();
              }	
    			});
    	alert = builder.create();
    	alert.show();
    }
    /*
    * shows the about dialogInterface
    * 
    * for some reason this does not work right now just so you know
    */
    private void show_about()
    {
    	AlertDialog alert;
    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
    	builder.setMessage(R.string.about)
    		.setCancelable(false)
    		.setTitle("About")
    		.setPositiveButton("OK", new DialogInterface.OnClickListener() 
    		{
    			public void onClick(DialogInterface dialog, int id) 
    			{
    				dialog.cancel();
    			}	
    		});
    	alert = builder.create();
    	alert.show();
    }
    /*
    * used for the preference menu
    */
    private void show_pref()
    {
    	
    }
    
    public void onRefreshClick(View view)
    {

        new Thread(new Runnable() {
            public void run() {
              Refresh(0);
            }
          }).start();
    }
    
    public void onClick(View view)
    {
    	try
    	{
    		
    		if (view == findViewById(R.id.buybuttontop0))
    		{
    			Intent i = new Intent(Intent.ACTION_VIEW,Uri.parse(buyUrl));
        		startActivity(i);
    		}
    		else if (view == findViewById(R.id.buybuttontop1))
    		{
    			Intent i = new Intent(Intent.ACTION_VIEW,Uri.parse(buyUrl1));
        		startActivity(i);
    		}
    		else if (view == findViewById(R.id.buybuttontop2))
    		{
    			Intent i = new Intent(Intent.ACTION_VIEW,Uri.parse(buyUrl2));
        		startActivity(i);
    		}
    		else if (view == findViewById(R.id.buybuttontop3))
    		{
    			Intent i = new Intent(Intent.ACTION_VIEW,Uri.parse(buyUrl3));
        		startActivity(i);
    		}
    		else if (view == findViewById(R.id.buybuttontop4))
    		{
    			Intent i = new Intent(Intent.ACTION_VIEW,Uri.parse(buyUrl4));
        		startActivity(i);
    		}
    	}
    	catch (Exception e)
    	{}
    }
    
    
    public void Refresh(final int d)
    {
    	try
        {
    		handler.post(new Runnable(){
    			public void run()
    			{
    				if(d == 0)
    					findViewById(R.id.progress0).setVisibility(View.VISIBLE);
    				else if (d == 1)
    					findViewById(R.id.progress1).setVisibility(View.VISIBLE);
    				else if (d == 2)
    					findViewById(R.id.progress2).setVisibility(View.VISIBLE);
    				else if (d == 3)
    					findViewById(R.id.progress3).setVisibility(View.VISIBLE);
    				else if (d == 4)
    					findViewById(R.id.progress4).setVisibility(View.VISIBLE);
    			}
    		});
    		
            // setup the url
    		URL url = null;
    	   if (d == 0)
    		   url = new URL(woot);
    	   else if (d == 1)
    		   url = new URL(shirt);
    	   else if (d == 2)
    		   url = new URL(wine);
    	   else if (d == 3)
    		   url = new URL(kids);
    	   else if (d == 4)
    		   url = new URL(sellout);

           // create the factory
           SAXParserFactory factory = SAXParserFactory.newInstance();
           // create a parser
           SAXParser parser = factory.newSAXParser();

           // create the reader (scanner)
           XMLReader xmlreader = parser.getXMLReader();
           // instantiate our handler
           RSSHandler theRssHandler = new RSSHandler();
           // assign our handler
           xmlreader.setContentHandler(theRssHandler);
           // get our data through the url class
           InputSource is = new InputSource(url.openStream());
           // perform the synchronous parse           
           xmlreader.parse(is);
           // get the results - should be a fully populated RSSFeed instance, 
		   // or null on error

			  String imageurl="";
           for(final Pair<String,String> pair: theRssHandler.nodes)
           {
        	   //condition
        	   //price
        	   //purchaseurl
        	   //soldout
        	   //wootoff
        	   //pubdate
        	   //standardimage
        	   //title
        	   //description
			  if(pair.a.equals("title"))
			  {
				  handler.post(new Runnable()
						  {
							  public void run()
							  {
								  if(d == 0)
									  ((TextView)findViewById(R.id.itemname0)).setText(pair.b);
								  else if(d == 1)
									  ((TextView)findViewById(R.id.itemname1)).setText(pair.b);
								  else if (d == 2)
									  ((TextView)findViewById(R.id.itemname2)).setText(pair.b);
								  else if (d == 3)
									  ((TextView)findViewById(R.id.itemname3)).setText(pair.b);
								  else if (d == 4)
									  ((TextView)findViewById(R.id.itemname4)).setText(pair.b);
							  }
						  });
			  }
			  else if(pair.a.equals("purchaseurl"))
			  {
				  if(d == 0)
					  buyUrl = pair.b;
				  else if (d == 1)
					  buyUrl1 = pair.b;
				  else if (d == 2)
					  buyUrl2 = pair.b;
				  else if (d == 3)
					  buyUrl3 = pair.b;
				  else if (d == 4)
					  buyUrl4 = pair.b;
			  }
			  else if(pair.a.equals("description"))
			  {
				  handler.post(new Runnable()
				  {
					  public void run()
					  {
						  if(d ==0)
							  ((WebView)findViewById(R.id.textcontent0)).loadDataWithBaseURL(null,pair.b, "text/html", "utf-8", null);
						  else if(d == 1)
							  ((WebView)findViewById(R.id.textcontent1)).loadDataWithBaseURL(null,pair.b, "text/html", "utf-8", null);
						  else if (d == 2)
							  ((WebView)findViewById(R.id.textcontent2)).loadDataWithBaseURL(null,pair.b, "text/html", "utf-8", null);
						  else if (d == 3)
							  ((WebView)findViewById(R.id.textcontent3)).loadDataWithBaseURL(null,pair.b, "text/html", "utf-8", null);
						  else if (d == 4)
							  ((WebView)findViewById(R.id.textcontent4)).loadDataWithBaseURL(null,pair.b, "text/html", "utf-8", null);
					  }
				  });
			  }
			  else if(pair.a.equals("price"))
			  {
				  handler.post(new Runnable()
				  {
					  public void run()
					  {
						  if(d == 0)
						  {
						      ((Button)findViewById(R.id.buybuttontop0)).setText("Buy Me!\n" + pair.b);
						  }
						  else if(d == 1)
						  {
					      	  ((Button)findViewById(R.id.buybuttontop1)).setText("Buy Me!\n" + pair.b);
						  }
						  else if(d == 2)
						  {
					      	  ((Button)findViewById(R.id.buybuttontop2)).setText("Buy Me!\n" + pair.b);
						  }
						  else if (d == 3)
						  {
					      	  ((Button)findViewById(R.id.buybuttontop3)).setText("Buy Me!\n" + pair.b);
						  }
						  else if (d == 4)
						  {
					      	  ((Button)findViewById(R.id.buybuttontop4)).setText("Buy Me!\n" + pair.b);
						  }
					  
					  
					  }
				  });
			  }
			  else if(pair.a.equals("standardimage"))
			  {
				  imageurl = pair.b;
			  }
           }
           
           final Bitmap bmImg = BitmapFactory.decodeStream(new URL(imageurl).openStream());
			  handler.post(new Runnable()
			  {
				  public void run()
				  {
					  if(d == 0)
						  ((ImageView)findViewById(R.id.image0)).setImageBitmap(bmImg);
					  else if(d == 1)
						  ((ImageView)findViewById(R.id.image1)).setImageBitmap(bmImg);
					  else if(d == 2)
						  ((ImageView)findViewById(R.id.image2)).setImageBitmap(bmImg);
					  else if(d == 3)
						  ((ImageView)findViewById(R.id.image3)).setImageBitmap(bmImg);
					  else if(d == 4)
						  ((ImageView)findViewById(R.id.image4)).setImageBitmap(bmImg);
				  }
			  });
			  
			  handler.post(new Runnable(){
	    			public void run()
	    			{
	    				if(d == 0)
	    					findViewById(R.id.progress0).setVisibility(View.INVISIBLE);
	    				else if(d == 1)
	    					findViewById(R.id.progress1).setVisibility(View.INVISIBLE);
	    				else if(d == 2)
	    					findViewById(R.id.progress2).setVisibility(View.INVISIBLE);
	    				else if(d == 3)
	    					findViewById(R.id.progress3).setVisibility(View.INVISIBLE);
	    				else if(d == 4)
	    					findViewById(R.id.progress4).setVisibility(View.INVISIBLE);
	    			}
	    		});
        }
        catch (Exception ee)
        {
        	ee.printStackTrace();
        }

    }
    
	
    @Override

    public boolean onTouchEvent(MotionEvent event) 
    {
      if (scanner.onTouchEvent(event))

        return true;

      else

        return false;
    }
    @Override
	public boolean onDown(MotionEvent arg0) 
    {
    	//Toast.makeText(this, "guesture bitches", Toast.LENGTH_SHORT).show();
    	// TODO Auto-generated method stub
    	return false;
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) 
	{
		//scroll right
		if(velocityX > 0)
		{
			flip.setInAnimation(inFromLeft()); 
			flip.setOutAnimation(outToRight());
			flip.showPrevious();
			//Toast.makeText(this, "greater", Toast.LENGTH_SHORT).show();
		}
		else if(velocityX < 0) //scroll left
		{
			flip.setInAnimation(inFromRight()); 
			flip.setOutAnimation(outToLeft());
			flip.showNext();
			//Toast.makeText(this, "lesser", Toast.LENGTH_SHORT).show();
		}
		return false;
	}

	@Override
	public void onLongPress(MotionEvent e) {
		// TODO Auto-generated method stub
		//Toast.makeText(this, "here", Toast.LENGTH_SHORT).show();
	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) 
	{
		return false;
	}

	@Override
	public void onShowPress(MotionEvent e) 
	{
		// TODO Auto-generated method stub
		//Toast.makeText(this, "onShowPress", Toast.LENGTH_SHORT).show();
	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) 
	{
		// TODO Auto-generated method stub
		//Toast.makeText(this, "onSingletap", Toast.LENGTH_SHORT).show();
		return false;
	}
	private Animation outToRight() 
	{
		Animation outtoRight = new TranslateAnimation(
				Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,  +1.0f,
				Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f
		);
		outtoRight.setDuration(500);
		outtoRight.setInterpolator(new AccelerateInterpolator());
		return outtoRight;
	}
	private Animation inFromRight() 
	{
		Animation inFromRight = new TranslateAnimation(
				Animation.RELATIVE_TO_PARENT,  +1.0f, Animation.RELATIVE_TO_PARENT,  0.0f,
				Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f
		);
		inFromRight.setDuration(500);
		inFromRight.setInterpolator(new AccelerateInterpolator());
		return inFromRight;
	}
	private Animation outToLeft() 
	{
		Animation outtoLeft = new TranslateAnimation(
				Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,  -1.0f,
				Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f
		);
		outtoLeft.setDuration(500);
		outtoLeft.setInterpolator(new AccelerateInterpolator());
		return outtoLeft;
	}

	private Animation inFromLeft() 
	{
		Animation inFromLeft = new TranslateAnimation(
				Animation.RELATIVE_TO_PARENT,  -1.0f, Animation.RELATIVE_TO_PARENT,  0.0f,
				Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f
		);
		inFromLeft.setDuration(500);
		inFromLeft.setInterpolator(new AccelerateInterpolator());
		return inFromLeft;
	}
	
}